<?php

namespace app\components;

use app\models\Setting;
use yii\base\Component;

class BaseSetting extends Component {

    protected $cacheKey = '__settings';
    protected $settings;

    public function init() {
        parent::init();

        $this->settings = \Yii::$app->cache->get($this->cacheKey);
        if (!$this->settings) {
            $this->settings = Setting::find()->asArray()->indexBy('id')->all();
            \Yii::$app->cache->set($this->cacheKey, $this->settings);
        }
    }

    public function get($name, $default = NULL) {
        return isset($this->settings[$name]) ? $this->settings[$name]['val'] : $default;
    }

    public function __get($name) {
        return $this->get($name, '');
    }

    public function flush() {
        $this->settings = Setting::find()->asArray()->indexBy('id')->all();
        \Yii::$app->cache->set($this->cacheKey, $this->settings);
    }
}